package com.example.lin.greendao.acitivity;


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.example.lin.greendao.R;
import com.example.lin.greendao.pojo.Student;
import com.example.lin.greendao.pojo.StudentDao;
import com.example.lin.greendao.utils.DBUtils;
import com.orhanobut.logger.Logger;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class MainActivity extends AppCompatActivity {


    @BindView(R.id.button1)
    Button button1;
    @BindView(R.id.button2)
    Button button2;
    @BindView(R.id.button3)
    Button button3;
    @BindView(R.id.button4)
    Button button4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

    }

    @OnClick({R.id.button1, R.id.button2, R.id.button3, R.id.button4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button1:
                addStudent();
                break;
            case R.id.button2:
                deleteStudent();
                break;
            case R.id.button3:
                updateStudent();
                break;
            case R.id.button4:
                queryStudents();
                break;
        }
    }

    private void updateStudent() {
        Student load = DBUtils.getSession().getStudentDao().load(2L);
        Logger.w(load.toString());


        load.setName("李四");//修改数据


        DBUtils.getSession().getStudentDao().update(load);//将修改的数据,写入到数据库表中
    }

    private void queryStudents() {

//        List<Student> students = DBUtils.getSession().getStudentDao().loadAll();

        List<Student> students = DBUtils.getSession().getStudentDao()
                .queryBuilder()
                .whereOr(StudentDao.Properties._id.le(4), StudentDao.Properties._id.gt(7))
                .build().list();
        for (Student stu : students) {
            Logger.w("student: %s", stu);
        }
    }

    private void deleteStudent() {
        DBUtils.getSession().getStudentDao().deleteByKey(5L);
        Logger.i("删除成功!");
    }

    private void addStudent() {
        Student s1 = new Student("张三", 12);
        long insert = DBUtils.getSession().getStudentDao().insert(s1);
        Logger.d("id : %s", insert);
    }


}
